package com.cicadamob.contact.api.Utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;

/**
 * ImageUtils
 * <ul>
 * convert between Bitmap, byte array, Drawable
 * <li>{@link #bitmapToByte(android.graphics.Bitmap)}</li>
 * <li>{@link #bitmapToDrawable(android.graphics.Bitmap)}</li>
 * <li>{@link #byteToBitmap(byte[])}</li>
 * <li>{@link #byteToDrawable(byte[])}</li>
 * <li>{@link #drawableToBitmap(android.graphics.drawable.Drawable)}</li>
 * <li>{@link #drawableToByte(android.graphics.drawable.Drawable)}</li>
 * </ul>
 * <ul>
 * scale image
 * <li>{@link #scaleImageTo(android.graphics.Bitmap, int, int)}</li>
 * <li>{@link #scaleImage(android.graphics.Bitmap, float, float)}</li>
 * </ul>
 * 
 * author yeyue
 * 14-9-16
 */
public class ImageUtils {

    /**
     * convert Bitmap to byte array
     * 
     * @param b
     * @return
     */
    public static byte[] bitmapToByte(Bitmap b) {
        if (b == null) {
            return null;
        }

        ByteArrayOutputStream o = new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.PNG, 100, o);
        return o.toByteArray();
    }

    /**
     * convert byte array to Bitmap
     * 
     * @param b
     * @return
     */
    public static Bitmap byteToBitmap(byte[] b) {
        return (b == null || b.length == 0) ? null : BitmapFactory.decodeByteArray(b, 0, b.length);
    }

    /**
     * convert Drawable to Bitmap
     * 
     * @param d
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable d) {
        return d == null ? null : ((BitmapDrawable)d).getBitmap();
    }

    /**
     * convert Bitmap to Drawable
     * 
     * @param b
     * @return
     */
    public static Drawable bitmapToDrawable(Bitmap b) {
        return b == null ? null : new BitmapDrawable(b);
    }

    /**
     * convert Drawable to byte array
     * 
     * @param d
     * @return
     */
    public static byte[] drawableToByte(Drawable d) {
        return bitmapToByte(drawableToBitmap(d));
    }

    /**
     * convert byte array to Drawable
     * 
     * @param b
     * @return
     */
    public static Drawable byteToDrawable(byte[] b) {
        return bitmapToDrawable(byteToBitmap(b));
    }

   
   
    /**
     * scale image
     * 
     * @param org
     * @param newWidth
     * @param newHeight
     * @return
     */
    public static Bitmap scaleImageTo(Bitmap org, int newWidth, int newHeight) {
        return scaleImage(org, (float)newWidth / org.getWidth(), (float)newHeight / org.getHeight());
    }

    /**
     * scale image
     * 
     * @param org
     * @param scaleWidth sacle of width
     * @param scaleHeight scale of height
     * @return
     */
    public static Bitmap scaleImage(Bitmap org, float scaleWidth, float scaleHeight) {
        if (org == null) {
            return null;
        }

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(org, 0, 0, org.getWidth(), org.getHeight(), matrix, true);
    }
    /**
     * scale image
     *
     * @param org    The bitmap we are subsetting
     * @param x The x coordinate of the first pixel in source
     * @param y The y coordinate of the first pixel in source
     * @param scaleWidth sacle of width
     * @param scaleHeight scale of height
     * @return
     */
    public static Bitmap scaleImage(Bitmap org,int x ,int y , float scaleWidth, float scaleHeight,int width,int height) {
        if (org == null) {
            return null;
        }

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(org, x, y, width, height, matrix, true);
    }
    /**合成 图片和字符串重重组图片
     * @param bitmap
     * @param string
     * @return bitmap
     */
    public static Bitmap compositionBitmap(Activity context,Bitmap bitmap,String string){
        if(bitmap==null){
            return null;
        }
        int w=bitmap.getWidth();
        int h=bitmap.getHeight();
        Matrix matrix = new Matrix();
//		DisplayMetrics displayMetrics = new DisplayMetrics();
//		context.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
//		float desity = displayMetrics.density;
        matrix.postScale(2.0f, 2.0f );
        bitmap = Bitmap.createBitmap(bitmap, 0,
                0,
                w,
                h, matrix, true);
        Paint p=new Paint();
        p.setColor(Color.WHITE);
        p.setAntiAlias(true);
        p.setTextSize(30.0f);
        p.setFilterBitmap(true);

        w=bitmap.getWidth();
        h=bitmap.getHeight();

        Bitmap newBitmap=Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas cv=new Canvas(newBitmap);
        cv.drawBitmap(bitmap, 0, 0,null);
        cv.drawText(string, (w-getFontlength(p, string))/2-5.0f, (h - getFontHeight(p))/2+getFontLeading(p)-5.0f, p);
        cv.save(Canvas.ALL_SAVE_FLAG);
        cv.restore();
        bitmap.recycle();
        return newBitmap;

    }
    /**
     * @return 返回指定笔和指定字符串的长度
     */
    private static float getFontlength(Paint paint, String str) {
        return paint.measureText(str);
    }
    /**
     * @return 返回指定笔的文字高度
     */
    private static float getFontHeight(Paint paint)  {
        Paint.FontMetrics fm = paint.getFontMetrics();
        return fm.descent - fm.ascent;
    }
    /**
     * @return 返回指定笔离文字顶部的基准距离
     */
    private static float getFontLeading(Paint paint)  {
        Paint.FontMetrics fm = paint.getFontMetrics();
        return fm.leading- fm.ascent;
    }
    /**把数据写入到图片中
     * @param path  图片路径    如（xxx/a.jpg）
     * @param name  整列数组
     * @return 
     */
    public static void writeExif (String path,String name ){
    
    	ExifInterface exifInterface;
		try {
			exifInterface = new ExifInterface(path);
		
    
			exifInterface.setAttribute(ExifInterface.TAG_MAKE, name);
		
    	
			exifInterface.saveAttributes();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
    /** 从exif文件读取数据
     * @param path  路径 如（xxx/a.jpg）
     * @param strings key 
     * @return  value 
     */
    @SuppressWarnings("null")
	public static String readExif(String path ){
    	
    	String value = null ;
    	
    	 try {
			ExifInterface exif = new ExifInterface(path);
			
				
				value=exif.getAttribute(ExifInterface.TAG_MAKE);
				
		
    	 
    	 
    	 
    	 } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    
    	return value;
    }

}
